﻿/**
PhiloGL
Copyright (c) 2011 Sencha Labs - Author: Nicolas Garcia Belmonte (http://philogb.github.com/)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/


//var pGL; //PhiloGL object
PhiloGL.unpack();
var gl;
var scene;
var atoms3D = []; //array of all atoms in the scene
var up = new PhiloGL.Vec3(0,1,0);

//www.senchalabs.org/philogl/PhiloGL/examples/lessons/1/
//http://www.senchalabs.org/philogl/PhiloGL/examples/lessons/11/

var mouseScale = 0.3;

function webGLStart() {
   
    //Create application
    PhiloGL(document.getElementById('graphicsCanvas'), {
        camera: {
            position: {
                x: 0, y: 0, z: -50
            }
        },

        events: {
            // r is the vector position of the camera

            // Mousewheel bound to zoom
            onMouseWheel: function (e) {
                e.stop();
                var camera = this.camera;
                var target = this.camera.target;
                var r = new PhiloGL.Vec3(camera.position.x,camera.position.y,camera.position.z).sub(new PhiloGL.Vec3(target.x,target.y,target.z));

                dR = r.unit().scale(-e.wheel);
                camera.position.x += dR.x;
                camera.position.y += dR.y;
                camera.position.z += dR.z;
                // camera.target.z += e.wheel;
                camera.update();
            },

            onDragStart: function(e) {
                pos = {
                    x: e.x,
                    y: e.y
                };
            },
            // Uncomment to bind left-click-drag to translate.
            // onDragMove: function (e) {
            //     var camera = this.camera;
            //     var target = this.camera.target;
            //     camera.position.x = mouseScale*(e.x-pos.x) + cameraStart.x;
            //     camera.position.y = -mouseScale*(e.y-pos.y) + cameraStart.y;
            //     target.x = mouseScale*(e.x-pos.x) + targetStart.x;
            //     target.y = -mouseScale*(e.y-pos.y) + targetStart.y;
            //     camera.update();
            // },

            // Uncomment to bind left-click-drag to rotate.

            // Rotation is done by unit vectors; there's some gimbol glitching at theta = 0 and pi, which will be solved whenever I get around to learning quaternions
            onDragMove: function (e) {
                var camera = this.camera;
                var target = this.camera.target;

                var r = new PhiloGL.Vec3(camera.position.x,camera.position.y,camera.position.z).sub(new PhiloGL.Vec3(target.x,target.y,target.z));
                var rXZ = new PhiloGL.Vec3(r.x,0,r.z);
                var sinPhi = -r.z/rXZ.norm();
                var cosPhi = -r.x/rXZ.norm();
                var sinTheta = rXZ.norm()/r.norm();

                // Unit vectors; phi is azimuth
                var phiHat = new PhiloGL.Vec3(-sinPhi,0,cosPhi);
                var thetaHat = phiHat.cross(r).unit();

                var dTheta = thetaHat.scale(e.y-pos.y).scale(mouseScale);
                var dPhi = phiHat.scale(-(e.x-pos.x)).scale(mouseScale);

                // Make the azimuthal rotation slower when we're close to the poles; prevent theta rotation when we're at the poles
                dPhi.$scale(sinTheta)

                if (Math.pow(r.x + dTheta.x,2) + Math.pow(r.y + dTheta.y,2) < 0.2) {
                    dTheta.$scale(0)
                };

                // Rotate, update the camera
                r = r.add(dPhi).add(dTheta).unit().scale(r.norm());
                camera.position.x = r.x+target.x;
                camera.position.y = r.y+target.y;
                camera.position.z = r.z+target.z;
                camera.update();

                // console.log(camera.position.x,camera.position.y,camera.position.z)
                pos = {
                    x: e.x,
                    y: e.y
                };
            },
        },



        onError: function () {
            alert("There was an error creating the app.");
        },

        onLoad: function (app) {
            //Unpack app properties
            gl = app.gl;
            var program = app.program;
            scene = app.scene;
            var canvas = app.canvas,
            camera = app.camera;

            //Basic gl setup
            gl.clearColor(0.0, 0.0, 0.0, 1.0);
            gl.clearDepth(1.0);
            gl.enable(gl.DEPTH_TEST);
            gl.depthFunc(gl.LEQUAL);
            gl.viewport(0, 0, +canvas.width, +canvas.height);
            gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
        }
    });


};

var atoms3D; //Contains all the atoms added to the scene

function clearScene() {
    for (var i = 0; i < atoms3D.length; i++) {
        scene.remove(atoms3D[i]);
    }

    atoms3D = [];
}

function drawAtoms(frame) {
    var atoms = frame.atoms;
    var atom;
    var atom3D;
    var color;

    for (var i = 0; i < atoms.length; i++)  //pdb.data.atoms.length
    {
        atom = atoms[i];

        // Choose the appropriate color for the atom
        if (atom.name.trim() === "N") {
            color = [0, 0, 1, 1];
        }
        else if (atom.name.trim() === "C") {
            color = [0, 100 / 255, 0, 1];
        }
        else if (atom.name.trim() === "O") {
            color = [1, 0, 0, 1];
        }
        else if (atom.name.trim() === "H") {
            color = [125 / 255, 249 / 255, 255 / 255, 1];
        }
        else if (atom.name.trim() === "S") {
            color = [1, 165 / 255, 0, 1];
        }
        else {
            color = [1, 0, 1, 1];
        }

        atom3D = new PhiloGL.O3D.Sphere({
                nlat: 30,
                nlong: 30,
                radius: .5,
                colors: color, //select appropriate colors
                pickable: true
            });

        atom3D.position = {
            x: atom.x,
            y: atom.y,
            z: atom.z
        };

        atom3D.update();

        scene.add(atom3D);


        atoms3D.push(atom3D); //add the O3D object to the scene objects list

        }
        draw();
};

function updateAtoms(frame) {
    var atoms = frame.atoms;
    var atom;
    for (var i = 0; i < atoms.length; i++)
    {
        atom = atoms[i]; //1-to-1 correspondence necessary

        atoms3D[i].position =
        {
            x: atom.x,
            y: atom.y,
            z: atom.z
        }

        atoms3D[i].update(); //update positions    
    }

    draw(); //redraw
};

//Draw the scene
function draw() {
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);


    var lightConfig = scene.config.lights;
    lightConfig.enable = true;
    lightConfig.ambient = {
        r: 0.2,
        g: 0.2,
        b: 0.2
    };
    lightConfig.directional.direction = {
        x: -1.0,
        y: -1.0,
        z: -1.0
    };
    lightConfig.directional.color = {
        r: 0.8,
        g: 0.8,
        b: 0.8
    };

    scene.render();
    PhiloGL.Fx.requestAnimationFrame(draw);
}